package com.huatao.auth.application.controller;

import com.alibaba.fastjson.JSON;
import com.google.common.base.Preconditions;
import com.huatao.auth.application.convert.AuthRolePermissionDTOConverter;
import com.huatao.auth.application.dto.AuthRolePermissionDTO;
import com.huatao.auth.domain.bo.AuthRolePermissionBO;
import com.huatao.auth.domain.service.AuthRolePermissionDomainService;
import com.huatao.auth.entity.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController
@RequestMapping("/rolePermission")
@Slf4j
public class RolePermissionController {

    @Resource
    private AuthRolePermissionDomainService authRolePermissionDomainService;

    @PostMapping("add")
    public Result<Boolean> add(@RequestBody AuthRolePermissionDTO authRolePermissionDTO) {
        try {
            if (log.isInfoEnabled()) {
                log.info("添加角色权限关系, authRolePermissionDTO={}", JSON.toJSONString(authRolePermissionDTO));
            }
            Preconditions.checkArgument(CollectionUtils.isEmpty(authRolePermissionDTO.getPermissionList()), "权限列表不能为空");
            Preconditions.checkNotNull(authRolePermissionDTO.getRoleId(), "角色ID不能为空");
            AuthRolePermissionBO authRolePermissionBO = AuthRolePermissionDTOConverter.INSTANCE.convertDtoToBo(authRolePermissionDTO);
            return Result.ok(authRolePermissionDomainService.add(authRolePermissionBO));
        } catch (Exception e) {
            log.error("添加角色权限关系失败", e);
            return Result.fail("添加角色权限关系失败");
        }
    }

}
